import React from 'react'
import Storage from "@react-native-community/async-storage";
import {Text, TextInput, ToastAndroid, TouchableOpacity, View} from "react-native";
import Style from "../../common/style";
import Title from "../component/title";

const KEY_TEST = 'key_test';

export default class StoragePage extends React.Component {

    state = {
        message: "",
        inputText: "",
    };

    render() {
        return (
            <View>
                <Title title='AsyncStorage'/>

                <Text style={Style.text}>
                    {this.state.message}
                </Text>

                <TextInput style={Style.input} placeholder='input value' onChangeText={
                    (text) => this.setState({inputText: text})
                }/>

                <TouchableOpacity style={Style.button} onPress={() => this.setStorageValue()}>
                    <Text>
                        保存数据
                    </Text>
                </TouchableOpacity>

                <TouchableOpacity style={Style.button} onPress={() => this.readStorageValue()}>
                    <Text>
                        获取数据
                    </Text>
                </TouchableOpacity>
            </View>
        )
    }

    async setStorageValue() {
        try {
            if(!this.state.inputText){
                ToastAndroid.show("please input",1500);
                return;
            }

            await Storage.setItem(KEY_TEST, this.state.inputText);
            this.setState({
                message: 'set value: ' + this.state.inputText,
            })
        } catch (e) {
            this.setState({
                message: 'set value error:' + e.message
            })
        }
    }

    async readStorageValue() {
        let name = await Storage.getItem(KEY_TEST);
        this.setState({
            message: 'read value :' + name
        })
    }
}
